import React from 'react';
import {
  Button, Checkbox, Col, Empty, Input,
  InputNumber, Layout, Modal, Popconfirm, Row,
  Select, Tabs, Tooltip, Tree,
} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { PageHeaderLayout, StandardTable, IconButton, PageCard } from '../../components';
import { modalWidth } from '../../../config';
import tools from '../../utils';
import Authorized from '../../utils/Authorized';
import styles from './special.css';

const types = require('../../assets/stureg_web/static/types.json');

const typeData = [];
for (let key in types) {
  typeData.push([key, types[key]]);
}

const reqApi = 'special';

const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const { Option } = Select;
const { TabPane } = Tabs;

const formItemLayout = {
  labelCol: { md: 3 },
  wrapperCol: { md: 21 },
};
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};

class page extends React.Component {
  state = {
    currentNavi: '',
    loading: false,
    visible: false,
    dialogLoading: false,
    dialogTitle: '',
    dialogAction: '',
    selectedRows: [],
    editId: 0,
    beforeName: '', // 编辑时记录初始值
    basicName: '专业',
  };

  componentDidMount() {
    this.funcGetAllData();
  }

  // 表格列
  columns = () => {
    const { props } = this;

    return [
      {
        title: '系部名称',
        dataIndex: 'pName',
      },
      {
        title: '专业名称',
        dataIndex: 'name',
        render: (text, record) => (
          <Authorized authority={() => tools.funcCheckValid(props, 'edit')} noMatch={text}>
            <a
              title="编辑"
              onClick={() => {
                this.setState({
                  editId: record.id,
                  basicName: '专业',
                }, () => this.funcOpenForm(record));
              }}
            >
              {text}
            </a>
          </Authorized>
        ),
      },
      {
        title: '报考类别',
        dataIndex: 'types',
        render: text => {
          const data = [];
          text.map((type) => {
            data.push(types[type]);
          });
          return data.toString();
        },
      },
      {
        title: '招生人数',
        dataIndex: 'quota',
        width: 100,
        render: text => text + ' 人',
      },
    ];
  };

  // 获取所有数据
  funcGetAllData = () => {
    this.setState({
      loading: true,
      selectedRows: [],
    });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listAll',
      payload: {
        currentPage: 1,
        pageSize: 1000,
      },
    }).then(() => this.setState({ loading: false }));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const { basicName, currentNavi } = this.state;
    const dialogAction = record ? "edit" : "create";
    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle(basicName, dialogAction),
      dialogAction,
    }, () => {
      const { props } = this;
      const isSpec = basicName === '专业';

      if (dialogAction === "edit") {
        const { name, sequ, remark, pid, types, quota } = record;
        const values = isSpec ?
          { name, sequ, remark, pid, types, quota } :
          { name, sequ, remark };
        props.form.setFieldsValue(values);
        this.setState({ beforeName: name });
      } else {
        props.form.resetFields();
        if (isSpec) props.form.setFieldsValue({ pid: currentNavi });
      }
    });
  };

  // 删除
  funcDelete = () => {
    const { state } = this;
    let names = [], ids = [];
    for (let i = 0; i < state.selectedRows.length; i += 1) {
      const item = state.selectedRows[i];
      const { id, name } = item;
      names.push(name);
      ids.push(id);
    }

    Modal.confirm({
      title: '删除？',
      content: (
        <div>
          <div>你即将删除以下记录：</div>
          <div>{names + ''}</div>
          <div>请确认是否删除？</div>
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => this.funcDeleteExecute(ids + ''),
    });
  };

  // 执行删除
  funcDeleteExecute = (ids) => {
    this.setState({ loading: true });

    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/dele',
      payload: { ids },
    }).then(() => {
      const { state, props } = this;
      const { success } = props[reqApi];
      if (success) {
        if (state.currentNavi === ids) {
          this.setState({ currentNavi: '' }, this.funcGetAllData);
        } else this.funcGetAllData();
      }
      else this.setState({ loading: false });
    });
  };

  // 保存
  funcSave = () => {
    const { dialogAction, editId } = this.state;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const model = { ...values };
      if (dialogAction === "edit") model.id = editId;

      try {
        model.types = JSON.stringify(model.types);
      } catch(e) {
        model.types = '[]';
      }

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/' + dialogAction,
        payload: { model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetAllData();
        }
      });
    });
  };

  // 树实体
  treeBody = (data) => {
    const { props } = this;
    const nodes = [];

    for (let i = 0; i < data.length; i += 1) {
      const item = data[i];
      const { id, name } = item;

      nodes.push(
        <TreeNode
          key={id}
          title={(
            <div className={styles.treeNode}>
              <label>{name}</label>
              <Authorized authority={() => tools.funcCheckValid(props, 'edit')}>
                <Tooltip title='编辑系部'>
                  <Icon
                    type="edit"
                    onClick={(e) => {
                      e.stopPropagation();
                      this.setState({
                        editId: id,
                        basicName: '系部',
                      }, () => this.funcOpenForm(item));
                    }}
                  />
                </Tooltip>
              </Authorized>
              <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
                <Popconfirm
                  title={"确定要删除“" + name + "”？"}
                  placement="right"
                  onConfirm={(e) => {
                    e.stopPropagation();
                    this.funcDeleteExecute(id);
                  }}
                  onCancel={(e) => e.stopPropagation()}
                >
                  <Tooltip title='删除系部'>
                    <Icon
                      type="delete"
                      onClick={(e) => e.stopPropagation()}
                    />
                  </Tooltip>
                </Popconfirm>
              </Authorized>
            </div>
          )}
        />,
      );
    }
    return nodes;
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const { allData, sysData } = props[reqApi];
    const createNavi = tools.funcCheckValid(props, 'create');

    return (
      <div>
        <Authorized authority={() => createNavi}>
          <div style={{ margin: (window.isMobile ? 0 : '16px') + ' 8px 8px 8px' }}>
            <IconButton
              text='新增系部'
              onClick={() => this.setState({
                basicName: '系部',
              }, () => this.funcOpenForm())}
            />
          </div>
        </Authorized>
        {allData.length ? (
          <div
            style={window.isMobile ? {} : {
              maxHeight: 'calc(100vh - ' + (createNavi ? 176 : 120) + 'px)',
              overflow: 'auto',
            }}
          >
            <Tree
              blockNode
              defaultExpandAll
              onSelect={(selectedKeys) => {
                this.setState({
                  currentNavi: selectedKeys.length ? selectedKeys[0] : "",
                });
              }}
            >
              {this.treeBody(sysData)}
            </Tree>
          </div>
        ) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    );
  };

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { specData } = props[reqApi];
    const data = [];
    for (let i = 0; i < specData.length; i += 1) {
      const item = specData[i];
      if (state.currentNavi && state.currentNavi !== item.pid) continue;
      data.push(item);
    }
    const total = data.length;

    return (
      <div>
        <Button.Group style={{ marginRight: 16 }}>
          <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
            <IconButton
              text={'新增' + (window.isMobile ? '' : '专业')}
              onClick={() => {
                this.setState({
                  basicName: '专业',
                }, () => this.funcOpenForm());
              }}
              style={{ marginBottom: 16 }}
            />
          </Authorized>
          <Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
            <IconButton
              text={'删除' + (window.isMobile ? '' : '专业')}
              type='danger'
              onClick={this.funcDelete}
              disabled={!state.selectedRows.length}
              style={{ marginBottom: 16 }}
            />
          </Authorized>
        </Button.Group>
        <span>
          {total ? '共 ' + total + ' 个专业' : '暂无专业, 请新增'}
        </span>
        <StandardTable
          columns={this.columns()}
          loading={state.loading}
          data={{
            list: data,
            pagination: false,
          }}
          selectedRows={state.selectedRows}
          onSelectRow={(selectedRows) => this.setState({ selectedRows })}
          scrollX={768}
        />
      </div>
    );
  };

  render() {
    const { state, props } = this;
    const { getFieldDecorator } = props.form;
    const { basicName } = state;

    return (
      <PageHeaderLayout title='系部和专业管理'>
        <PageCard
          bodyStyle={{ padding: window.isMobile ? '0 8px' : 0 }}
          children={window.isMobile ? (
            <Tabs>
              <TabPane tab='系部管理' key='sys' >{this.naviMenu()}</TabPane>
              <TabPane tab='专业管理' key='spec'>{this.contentTable()}</TabPane>
            </Tabs>
          ) : (
            <Layout>
              <Sider
                theme="light"
                style={{ borderRight: "1px solid gainsboro" }}
              >
                {this.naviMenu()}
              </Sider>
              <Content
                style={{
                  padding: '16px 0 0 8px',
                  backgroundColor: 'white',
                }}
              >
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Modal
          width={modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          bodyStyle={{ paddingBottom: 0 }}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              loading={state.dialogLoading}
              onClick={this.funcSave}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={12} sm={24}>
                <Form.Item label={basicName + '名称'} {...formItemLayout2}>
                  {getFieldDecorator("name", {
                    rules: [{ required: true, message: '请输入' + basicName + '名称' }],
                  })(<Input maxLength={20} autoFocus />)}
                </Form.Item>
              </Col>

              {basicName === '专业' ? (
                <>
                <Col md={12} sm={24}>
                  <Form.Item label='所属系部' {...formItemLayout2}>
                    {getFieldDecorator('pid', {
                      rules: [{ required: true, message: '请选择系部' }],
                    })(
                      <Select>
                        {props[reqApi].sysData.map((item) => {
                          const { id, name } = item;
                          return <Option key={id} value={id}>{name}</Option>;
                        })}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item label='报考类别' {...formItemLayout}>
                    {getFieldDecorator('types')(
                      <Checkbox.Group
                        options={typeData.map(([value, label]) => {
                          return { label, value };
                        })}
                      />
                    )}
                  </Form.Item>
                </Col>
                <Col md={12} sm={24}>
                  <Form.Item label='招生人数' {...formItemLayout2}>
                    {getFieldDecorator('quota', {
                      initialValue: 0,
                    })(<Input type='number' min={0} max={1000} step={10} suffix='人' />)}
                  </Form.Item>
                </Col>
                </>
              ) : null}

              <Col md={12} sm={24}>
                <Form.Item label="显示顺序" {...formItemLayout2}>
                  {getFieldDecorator("sequ", {
                    initialValue: 0,
                  })(<InputNumber min={0} max={1000} style={{ width: '100%' }} />)}
                </Form.Item>
              </Col>

              <Col span={24}>
                <Form.Item label="备注" {...formItemLayout}>
                  {getFieldDecorator("remark")(
                    <Input.TextArea maxLength={255} autoSize={{ minRows: 3, maxRows: 5 }} />
                  )}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ special, menu }) => ({ special, menu }))(page2);
